package cn.edu.sgu.www.mhxysy.redis.repository.impl;

import cn.edu.sgu.www.mhxysy.consts.RedisKeyPrefixes;
import cn.edu.sgu.www.mhxysy.entity.server.Area;
import cn.edu.sgu.www.mhxysy.mapper.server.AreaMapper;
import cn.edu.sgu.www.mhxysy.redis.RedisUtils;
import cn.edu.sgu.www.mhxysy.redis.repository.RedisRepository;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
@Component
public class AreaRepository implements RedisRepository {

    private final RedisUtils redisUtils;
    private final AreaMapper areaMapper;

    public AreaRepository(RedisUtils redisUtils, AreaMapper areaMapper) {
        this.redisUtils = redisUtils;
        this.areaMapper = areaMapper;
    }

    @Override
    public void put(String id, Object value) {
        String key = RedisKeyPrefixes.PREFIX_AREA + id;

        if (value == null) {
            redisUtils.set(key, null);
        } else {
            redisUtils.set(key, JSON.toJSONString(value));
        }

        redisUtils.expire(key, 7, TimeUnit.DAYS);
    }

    @Override
    public Area selectById(String id) {
        String key = RedisKeyPrefixes.PREFIX_AREA + id;

        if (redisUtils.hasKey(key)) {
            String value = redisUtils.get(key);

            log.debug("命中缓存{}", key);

            if (value != null) {
                return JSON.parseObject(value, Area.class);
            }

            return null;
        }

        Area area = areaMapper.selectById(id);

        put(id, area);

        return area;
    }

    @Override
    public void putList(Object value) {
        String key = RedisKeyPrefixes.PREFIX_AREAS;

        redisUtils.set(key, JSON.toJSONString(value), 7, TimeUnit.DAYS);
    }

    @Override
    public List<Area> selectList() {
        String key = RedisKeyPrefixes.PREFIX_AREAS;

        if (redisUtils.hasKey(key)) {
            String value = redisUtils.get(key);

            log.debug("命中缓存{}", key);

            return JSON.parseArray(value, Area.class);
        }

        List<Area> list = areaMapper.selectList(null);

        putList(list);

        return list;
    }

    @Override
    public void deleteList() {
        String key = RedisKeyPrefixes.PREFIX_AREAS;

        redisUtils.delete(key);
    }

    @Override
    public void deleteById(String primaryKey) {
        String key = RedisKeyPrefixes.PREFIX_AREA + primaryKey;

        redisUtils.delete(key);
    }

}